package com.wuwei.elearning.jiwu;

import com.alibaba.excel.EasyExcel;
import com.wuwei.elearning.question.domain.Question;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通过题号获取题目的测试类
 */
public class PoJieQuestion {



    private   Map<String,String> header = new HashMap<>();

    private  List<String> keys = new ArrayList<>();

    private   Map<String,String> body = new HashMap<>();

    public static String subject;


    private List<Question> questions = new ArrayList<>();





    private void write(List<Question> uniqueQuestions) {
        EasyExcel.write("question.xlsx", Question.class)
                .sheet("模板")
                .doWrite(uniqueQuestions);
    }



    /**
     * 模拟在机务在线网站回顾试卷时，处于加载模式下，往下拉的行为，使用java来向机务在线发起请求
     * @param records
     * @param eachnum
     * @throws Exception
     */
    public  void  getJuWu (String records,String id,String eachnum,String juanHao) throws Exception {
        System.out.println("试卷编号为:"+juanHao);
        this.getHead();
        this.getBody();
        body.put("id",id);
        body.put("records",records);
        body.put("eachnum",eachnum);
        Map<String,String> query = new HashMap<>();
        query.put("a","ajax");
        HttpResponse post = HttpUtils.doPost("https://www.airacm.com", "/learning.php", "POST", header, query, body);
        HttpEntity entity = post.getEntity();
        if (post.containsHeader(HTTP.CONTENT_ENCODING)) {
            entity = new GzipDecompressingEntity(entity);  // Gzip解压缩
        }
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            if ("综合阅读".equals(subject)){
                this.deCodeHtmlForM9(responseString);
            } else {
                this.deCodeHtml(responseString);
                // 处理响应体内容
            }

        }
        this.write(questions);
    }



    /**
     * 添加请请求头，该请求头用于https://www.airacm.com/learning.php?a=ajax这种请求
     * 这里注意，请求体保存在txt文件中，文件中不要有Content-Length=76这个参数
     */
    @SneakyThrows
    public void getHead() {
        this.header = new HashMap<>();
        this.keys = new ArrayList<>();
        String fileName = "GetQuestion/header.txt";
        FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line = bufferedReader.readLine();
        while (line!=null){
//            System.out.println(line);
            if (line.length() > 1) {
                int i = line.indexOf(":");
//                System.out.println(line.substring(0,i));
                this.keys.add(line.substring(0,i));
//                System.out.println(line.substring(i+2));
                this.header.put(line.substring(0,i),line.substring(i + 2));
            }
            line = bufferedReader.readLine();
        }
        this.header.put("Cookie",MyData.getCookie());
    }

    /**
     * 添加请求体，请求体为q=view&id=8953660&records=27589%3B27716%3B27720%3B27727%3B27728%3B&eachnum=0，这种格式
     * 这里要注意这个27589，27716，这些代表一道道题目编号
     * 这个id=8953660代表试卷编号
     */
    @SneakyThrows
    public void getBody(){
        body = new HashMap<>();
        String fileName = "GetQuestion/body.txt";
        FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line = bufferedReader.readLine();
        String[] split = line.split("&");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            int i1 = s.indexOf("=");
            String key = s.substring(0, i1);
            String values = s.substring(i1+1);
            this.body.put(key,values);
        }
    }

    /**
     * M9英语的题目解析方法
     * @param responseString
     */
    private void deCodeHtmlForM9(String responseString) {
        List<Question> list = new ArrayList<>();
        // 解析HTML文档
        Document doc = Jsoup.parse(responseString);
        Elements h1 = doc.select("h1");
        for (Element element : h1) {
            String text = element.text();
            Question question = new Question();
            question.setQuestion(text);
            list.add(question);
        }
        Elements li = doc.select("li");
        for (int i = 0; i < li.size(); i++) {
            Element element = li.get(i);
            String text1 = element.text();
            int a = i % 3;
            int b = i / 3;
            if (a==0) {
                list.get(b).setItem1(text1);
            } else if (a == 1) {
                list.get(b).setItem2(text1);
            } else {
                list.get(b).setItem3(text1);
            }
        }

        Elements span = doc.select("span.ui-images-maxwidth-limit");
        for (int i = 0; i < span.size(); i++) {
            Element element = span.get(i);
            String text = element.text();
            list.get(i).setRemark(text);
        }


        for (int i = 0; i < list.size(); i++) {
            Question question = list.get(i);
            String item1 = question.getItem1();
            String item2 = question.getItem2();
            String item3 = question.getItem3();
            String answer = "";

            if (item1.endsWith("×")) {
                item1 = item1.substring(0, item1.length() - 1);
                question.setItem1(item1);
            }
            if (item2.endsWith("×")) {
                item2 = item1.substring(0, item1.length() - 1);
                question.setItem2(item2);
            }
            if (item3.endsWith("×")) {
                item3 = item1.substring(0, item1.length() - 1);
                question.setItem3(item3);
            }

            if (item1==null) {
                System.out.println("程序报错");
                System.out.println(doc);
                continue;
            }
            if (item1.endsWith("◎") || item1.endsWith("√")) {
                String substring = item1.substring(0, item1.length() - 1);
                question.setItem1(substring);
                answer += item1.charAt(0);
            }
            if (item2.endsWith("◎") || item2.endsWith("√")) {
                String substring = item2.substring(0, item2.length() - 1);
                question.setItem2(substring);
                if ("".equals(answer)) {
                    answer += item2.charAt(0);
                } else {
                    answer += "+" + item2.charAt(0);
                }
            }
            if (item3.endsWith("◎") || item3.endsWith("√")) {
                String substring = item3.substring(0, item3.length() - 1);
                question.setItem3(substring);
                if ("".equals(answer)) {
                    answer += item3.charAt(0);
                } else {
                    answer += "+" + item3.charAt(0);
                }
            }
            question.setAnswer(answer);
            String question1 = question.getQuestion();
            int indexOf = question1.indexOf(".");
            if (indexOf < 4) {
                String substring = question1.substring(indexOf + 1);
                question.setQuestion(substring);
            }
            if (subject == null) {
                subjectId = subjectMapper.getIdByName(subject);
            }
            question.setSubjectId(subjectId);
//            System.out.println(question);
//            questionMapper.insert(question);
            questions.add(question);
        }
    }

    @Resource
    private SubjectMapper subjectMapper;

    private Long subjectId;

    /**
     * 当在机务在线的错题回顾时，处于加载模式下，机务在线的网站会返回一个html格式的文件，而该文件里就有一道道提，本方法用于提取其中文字
     * 提取html里的文字，将该文字存储到数据库中
     * @param responseString
     */
    public void deCodeHtml(String responseString) {
        List<Question> list = new ArrayList<>();
        // 解析HTML文档
        Document doc = Jsoup.parse(responseString);
        Elements h1 = doc.select("h1");
        for (Element element : h1) {
            String text = element.text();
            Question question = new Question();
            question.setQuestion(text);
            list.add(question);
        }
        Elements li = doc.select("li");
        for (int i = 0; i < li.size(); i++) {
            Element element = li.get(i);
            String text1 = element.text();
            int a = i % 4;
            int b = i / 4;
            if (a==0) {
                list.get(b).setItem1(text1);
            } else if (a == 1) {
                list.get(b).setItem2(text1);
            } else if (a == 2) {
                list.get(b).setItem3(text1);
            } else {
                list.get(b).setItem4(text1);
            }
        }

        Elements span = doc.select("span.ui-images-maxwidth-limit");
        for (int i = 0; i < span.size(); i++) {
            Element element = span.get(i);
            String text = element.text();
            list.get(i).setRemark(text);
        }


        for (int i = 0; i < list.size(); i++) {
            Question question = list.get(i);
            String item1 = question.getItem1();
            String item2 = question.getItem2();
            String item3 = question.getItem3();
            String item4 = question.getItem4();
            if (item1.endsWith("×")) {
                item1 = item1.substring(0, item1.length() - 1);
                question.setItem1(item1);
            }
            if (item2.endsWith("×")) {
                item2 = item1.substring(0, item1.length() - 1);
                question.setItem2(item2);
            }
            if (item3.endsWith("×")) {
                item3 = item1.substring(0, item1.length() - 1);
                question.setItem3(item3);
            }
            if (item4!=null&&item4.endsWith("×")) {
                item4 = item1.substring(0, item1.length() - 1);
                question.setItem4(item4);
            }
            String answer = "";
            if (item1==null) {
                System.out.println("程序报错");
                System.out.println(doc);
                continue;
            }
            if (item1.endsWith("◎") || item1.endsWith("√")) {
                String substring = item1.substring(0, item1.length() - 1);
                question.setItem1(substring);
                answer += item1.charAt(0);
            }
            if (item2.endsWith("◎") || item2.endsWith("√")) {
                String substring = item2.substring(0, item2.length() - 1);
                question.setItem2(substring);
                if ("".equals(answer)) {
                    answer += item2.charAt(0);
                } else {
                    answer += "+" + item2.charAt(0);
                }
            }
            if (item3.endsWith("◎") || item3.endsWith("√")) {
                String substring = item3.substring(0, item3.length() - 1);
                question.setItem3(substring);
                if ("".equals(answer)) {
                    answer += item3.charAt(0);
                } else {
                    answer += "+" + item3.charAt(0);
                }
            }
            //现在因为英语没有选项4，加一个条件防止报错
            if (item4!=null&&(item4.endsWith("◎") || item4.endsWith("√"))) {
                String substring = item4.substring(0, item4.length() - 1);
                question.setItem4(substring);
                if ("".equals(answer)) {
                    answer += item4.charAt(0);
                } else {
                    answer += "+" + item4.charAt(0);
                }
            }
            question.setAnswer(answer);
            String question1 = question.getQuestion();
            int indexOf = question1.indexOf(".");
            if (indexOf < 4) {
                String substring = question1.substring(indexOf + 1);
                question.setQuestion(substring);
            }
            if (subject == null) {
                subjectId = subjectMapper.getIdByName(subject);
            }
            question.setSubjectId(subjectId);
//            System.out.println(question);
//            questionMapper.insert(question);
            questions.add(question);
        }
    }
}
